<template>
  <div class="h-full bg-slate-50 p-6 overflow-y-auto">

    <div class="text-center mb-6 p-6 bg-white rounded-lg shadow-sm">
      <h2 class="flex items-center justify-center gap-3 text-2xl font-semibold text-gray-800 mb-2">
        <n-icon class="text-3xl text-blue-500" :component="PeopleTeamIcon" />
        <span>{{ pageTitle }}</span>
      </h2>
      <p class="text-gray-500">{{ pageSubtitle }}</p>
    </div>

    <div class="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
      <div class="flex items-center gap-3 mb-3">
        <n-icon class="text-xl text-blue-600" :component="InfoIcon" />
        <h3 class="text-md font-semibold text-blue-800">操作提示</h3>
      </div>
      <div v-if="props.mode === 'transition'" class="space-y-2 text-sm text-blue-700">
        <p>• **换届操作**：请为即将卸任的支委设置一个准确的“结束日期”。</p>
        <p>• 同时，完整填写新一届支委的“开始日期”和所有成员信息。</p>
      </div>
      <div v-else class="space-y-2 text-sm text-blue-700">
        <p>• **编辑操作**：您可以修改当前支委的“开始日期”或调整成员列表。</p>
        <p>• 所有修改将直接应用到当前这一届支委信息上。</p>
      </div>
    </div>

    <n-form v-if="props.mode === 'transition'" ref="formRefTransition">
      <n-space vertical :size="24">
        <n-card v-if="hasCurrentCommittee" class="rounded-lg shadow-sm" :bordered="false">
          <template #header>
            <div class="flex items-center gap-3">
              <n-icon class="text-xl text-orange-500" :component="LogOutIcon" />
              <span class="text-lg font-semibold text-gray-800">卸任支委信息</span>
            </div>
          </template>
          <div v-if="currentCommitteeInfo" class="mb-4 p-3 bg-orange-50 rounded-lg">
            <p class="text-sm text-orange-700 mb-2">当前支委信息：</p>
            <div class="text-sm text-gray-600">
              <p>开始日期：{{ formatDate(currentCommitteeInfo.startDate) }}</p>
              <p>成员人数：{{ currentCommitteeInfo.committeeMembers?.length || 0 }} 人</p>
            </div>
          </div>
          <n-form-item label="任期结束日期" path="endDate">
            <n-date-picker
              v-model:formatted-value="formValueTransition.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="请选择当前届的结束日期"
            />
          </n-form-item>
        </n-card>

        <n-card class="rounded-lg shadow-sm" :bordered="false">
          <template #header>
            <div class="flex items-center gap-3">
              <n-icon class="text-xl text-green-500" :component="LogInIcon" />
              <span class="text-lg font-semibold text-gray-800">新任支委信息</span>
            </div>
          </template>
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="24" label="新任期开始日期" path="newCommittee.startDate">
              <n-date-picker
                v-model:formatted-value="formValueTransition.newCommittee.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="请选择新一届的开始日期"
                @update:value="handleStartDateChange"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="新一届支委成员" path="newCommittee.committeeMembers">
              <n-alert v-if="!formValueTransition.newCommittee.startDate" type="info" class="mb-4">
                请先选择新任期开始日期，然后再添加支委成员
              </n-alert>
              <div v-else class="space-y-3">
                <div v-for="(member, index) in formValueTransition.newCommittee.committeeMembers" :key="index" class="p-4 border rounded-lg bg-white">
                  <div class="flex items-center gap-4 mb-3">
                    <n-select
                      v-model:value="member.memberId"
                      :options="hardcodedOptions"
                      placeholder="选择党员"
                      filterable
                      clearable
                      class="flex-1"
                      @update:value="(value) => handleMemberSelect(index, value)"
                      :loading="false"
                      :disabled="false"
                    />
                    <!-- 临时调试：显示选项数量 -->
                    <div class="text-xs text-gray-500 mt-1">
                      硬编码选项数量: {{ hardcodedOptions.length }},
                      计算选项数量: {{ availableMembersOptions.length }}
                    </div>
                    <n-select
                      v-model:value="member.positionHeld"
                      :options="positionOptions"
                      placeholder="担任职务"
                      class="min-w-[150px]"
                      :disabled="!member.memberId"
                    />
                    <n-button type="error" size="small" @click="removeCommitteeMember(index)">
                      <template #icon><n-icon><trash-outline /></n-icon></template>
                    </n-button>
                  </div>
                  <!-- 显示选中党员的详细信息 -->
                  <div v-if="member.memberId && getSelectedMemberInfo(member.memberId)" class="p-3 bg-gray-50 rounded-md text-sm">
                    <div class="grid grid-cols-3 gap-4">
                      <div>
                        <span class="text-gray-500">姓名：</span>
                        <span class="font-medium">{{ getSelectedMemberInfo(member.memberId).memberName }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">班级：</span>
                        <span class="font-medium">{{ getSelectedMemberInfo(member.memberId).class }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">学号：</span>
                        <span class="font-medium">{{ getSelectedMemberInfo(member.memberId).studentId }}</span>
                      </div>
                    </div>
                    <div class="mt-2">
                      <span class="text-gray-500">政治面貌：</span>
                      <n-tag :type="getSelectedMemberInfo(member.memberId).politicalStatus === '正式党员' ? 'success' : 'warning'" size="small">
                        {{ getSelectedMemberInfo(member.memberId).politicalStatus }}
                      </n-tag>
                    </div>
                  </div>
                </div>
                <n-button type="primary" dashed @click="addCommitteeMember">
                  <template #icon><n-icon><add-outline /></n-icon></template>
                  添加支委成员
                </n-button>
              </div>
            </n-form-item-gi>
          </n-grid>
        </n-card>
      </n-space>
    </n-form>

    <n-form v-else ref="formRefEdit" :model="formValueEdit" :rules="rulesEdit">
        <n-card class="rounded-lg shadow-sm" :bordered="false">
          <template #header>
            <div class="flex items-center gap-3">
              <n-icon class="text-xl text-blue-500" :component="EditIcon" />
              <span class="text-lg font-semibold text-gray-800">支委信息</span>
            </div>
          </template>
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="24" label="任期开始日期" path="startDate">
               <n-date-picker
                v-model:formatted-value="formValueEdit.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="请选择本届的开始日期"
                @update:value="handleEditStartDateChange"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="支委成员" path="committeeMembers">
              <n-alert v-if="!formValueEdit.startDate" type="info" class="mb-4">
                请先选择任期开始日期，然后再添加支委成员
              </n-alert>
              <div v-else class="space-y-3">
                <div v-for="(member, index) in formValueEdit.committeeMembers" :key="index" class="p-4 border rounded-lg bg-white">
                  <div class="flex items-center gap-4 mb-3">
                    <n-select
                      v-model:value="member.memberId"
                      :options="hardcodedOptions"
                      placeholder="选择党员"
                      filterable
                      clearable
                      class="flex-1"
                      @update:value="(value) => handleMemberSelect(index, value)"
                      :loading="false"
                      :disabled="false"
                    />
                    <!-- 临时调试：显示选项数量 -->
                    <div class="text-xs text-gray-500 mt-1">
                      硬编码选项数量: {{ hardcodedOptions.length }},
                      计算选项数量: {{ availableMembersOptions.length }}
                    </div>
                    <n-select
                      v-model:value="member.positionHeld"
                      :options="positionOptions"
                      placeholder="担任职务"
                      class="min-w-[150px]"
                      :disabled="!member.memberId"
                    />
                    <n-button type="error" size="small" @click="removeCommitteeMember(index)">
                      <template #icon><n-icon><trash-outline /></n-icon></template>
                    </n-button>
                  </div>
                  <!-- 显示选中党员的详细信息 -->
                  <div v-if="member.memberId && getSelectedMemberInfo(member.memberId)" class="p-3 bg-gray-50 rounded-md text-sm">
                    <div class="grid grid-cols-3 gap-4">
                      <div>
                        <span class="text-gray-500">姓名：</span>
                        <span class="font-medium">{{ getSelectedMemberInfo(member.memberId).memberName }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">班级：</span>
                        <span class="font-medium">{{ getSelectedMemberInfo(member.memberId).class }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">学号：</span>
                        <span class="font-medium">{{ getSelectedMemberInfo(member.memberId).studentId }}</span>
                      </div>
                    </div>
                    <div class="mt-2">
                      <span class="text-gray-500">政治面貌：</span>
                      <n-tag :type="getSelectedMemberInfo(member.memberId).politicalStatus === '正式党员' ? 'success' : 'warning'" size="small">
                        {{ getSelectedMemberInfo(member.memberId).politicalStatus }}
                      </n-tag>
                    </div>
                  </div>
                </div>
                <n-button type="primary" dashed @click="addCommitteeMember">
                  <template #icon><n-icon><add-outline /></n-icon></template>
                  添加支委成员
                </n-button>
              </div>
            </n-form-item-gi>
          </n-grid>
        </n-card>
    </n-form>

  </div>
</template>

<script setup>
import { ref, onMounted, computed, h } from 'vue';
import {
  NForm, NFormItem, NFormItemGi, NInput, NSelect, NDatePicker,
  NCard, NGrid, NSpace, NIcon, NButton, NTag, NTooltip
} from 'naive-ui';
import {
  People as PeopleTeamIcon,
  InformationCircleOutline as InfoIcon,
  CreateOutline as EditIcon,
  LogInOutline as LogInIcon,
  LogOutOutline as LogOutIcon,
  AddOutline,
  TrashOutline,
  PersonOutline,
  CallOutline,
  SchoolOutline
} from '@vicons/ionicons5';

const props = defineProps({
  mode: { type: String, required: true, default: 'edit' }, // 'add', 'edit', 'transition'
  initialData: { type: Object, default: null },
  branchData: { type: Object, default: null }
});

// 检查是否有当前支委
const hasCurrentCommittee = computed(() => {
  return props.initialData && !props.initialData.endDate;
});

// 当前支委信息
const currentCommitteeInfo = computed(() => {
  return hasCurrentCommittee.value ? props.initialData : null;
});

// --- 表单 Refs ---
const formRefEdit = ref(null);
const formRefTransition = ref(null);

// --- 动态标题 ---
const pageTitle = computed(() => {
  const titles = {
    add: '新增支委',
    edit: '编辑当前支委',
    transition: '支委换届'
  };
  return titles[props.mode] || '编辑支委信息';
});
const pageSubtitle = computed(() => {
  const subtitles = {
    add: '请设置新一届支委的任期和成员',
    edit: '修改当前在任支委的详细信息',
    transition: '结束当前任期并开启新一届支委'
  };
  return subtitles[props.mode] || '管理支委信息';
});


// --- 表单数据模型 ---
const formValueEdit = ref({
  startDate: null,
  committeeMembers: []
});
const formValueTransition = ref({
  endDate: null,
 // 原始数据，用于记录ID等，便于后端更新
  originalCommittee: {}, 
  newCommittee: {
    startDate: null,
    committeeMembers: []
  }
});

// --- 表单规则 ---
const rulesEdit = {
  startDate: { required: true, message: '请选择任期开始日期', trigger: 'change' },
  committeeMembers: { required: true, type: 'array', min: 1, message: '至少需要一名支委成员', trigger: 'change' }
};
// 换届的规则可以更细化，这里做简化处理
const rulesTransition = {
  // ... 可根据需要添加
};

// --- 支委职务选项 ---
const positionOptions = [
  { label: '支部书记', value: '支部书记' },
  { label: '副书记', value: '副书记' },
  { label: '组织委员', value: '组织委员' },
  { label: '宣传委员', value: '宣传委员' },
  { label: '纪检委员', value: '纪检委员' },
];

// --- 硬编码选项用于测试 ---
const hardcodedOptions = [
  { label: '张三 (2021001)', value: 'M001' },
  { label: '李四 (2021002)', value: 'M002' },
  { label: '王五 (2021003)', value: 'M003' },
  { label: '赵六 (2021004)', value: 'M004' },
  { label: '钱七 (2021005)', value: 'M005' }
];

// --- 测试数据 ---
const mockMembers = [
  {
    memberId: 'M001',
    memberName: '张三',
    studentId: '2021001',
    class: '计算机科学与技术1班',
    politicalStatus: '正式党员',
    enrollmentStatus: '在读',
    phoneNumber: '13800138001',
    joinPartyDate: '2021-05-20',
    availableStartDate: '2023-09-01'
  },
  {
    memberId: 'M002',
    memberName: '李四',
    studentId: '2021002',
    class: '计算机科学与技术2班',
    politicalStatus: '正式党员',
    enrollmentStatus: '在读',
    phoneNumber: '13800138002',
    joinPartyDate: '2021-06-15',
    availableStartDate: '2023-09-01'
  },
  {
    memberId: 'M003',
    memberName: '王五',
    studentId: '2021003',
    class: '软件工程1班',
    politicalStatus: '预备党员',
    enrollmentStatus: '在读',
    phoneNumber: '13800138003',
    joinPartyDate: '2022-03-10',
    availableStartDate: '2024-01-01'
  },
  {
    memberId: 'M004',
    memberName: '赵六',
    studentId: '2021004',
    class: '软件工程2班',
    politicalStatus: '正式党员',
    enrollmentStatus: '在读',
    phoneNumber: '13800138004',
    joinPartyDate: '2021-11-25',
    availableStartDate: '2023-09-01'
  },
  {
    memberId: 'M005',
    memberName: '钱七',
    studentId: '2021005',
    class: '信息安全1班',
    politicalStatus: '预备党员',
    enrollmentStatus: '在读',
    phoneNumber: '13800138005',
    joinPartyDate: '2022-09-18',
    availableStartDate: '2024-03-01'
  }
];

// --- 党员选项 ---
const availableMembersOptions = computed(() => {
  // 添加一个测试选项，确保有内容显示
  const testOptions = [
    { label: '测试选项1', value: 'test1' },
    { label: '测试选项2', value: 'test2' }
  ];
  
  // 直接使用测试数据
  let members = [...mockMembers];
  
  // 根据当前模式获取选择的开始日期
  let selectedDate = null;
  if (props.mode === 'transition') {
    if (formValueTransition.value.newCommittee.startDate) {
      selectedDate = new Date(formValueTransition.value.newCommittee.startDate);
    }
  } else {
    if (formValueEdit.value.startDate) {
      selectedDate = new Date(formValueEdit.value.startDate);
    }
  }
  
  // 如果选择了开始日期，进一步过滤可用的党员
  if (selectedDate) {
    members = members.filter(member => {
      // 对于测试数据，检查 availableStartDate
      const availableDate = member.availableStartDate ? new Date(member.availableStartDate) : new Date('2020-01-01');
      return availableDate <= selectedDate;
    });
  }
  
  // 转换为选项格式
  const memberOptions = members.map(member => ({
    label: `${member.memberName} (${member.studentId})`,
    value: member.memberId,
    member: member
  }));
  
  // 添加调试日志
  console.log('availableMembersOptions:', memberOptions);
  console.log('selectedDate:', selectedDate);
  console.log('mode:', props.mode);
  
  // 如果没有成员选项，返回测试选项
  return memberOptions.length > 0 ? memberOptions : testOptions;
});

// 自定义渲染选项，添加hover提示
const renderMemberOption = (option) => {
  // 简化渲染函数，直接返回label
  return option.label || '未知党员';
};

// --- 动态成员列表 ---
const createNewMember = () => ({
  memberId: null,
  memberName: '',
  positionHeld: null,
  phoneNumber: ''
});

// --- 处理开始日期变化 ---
const handleStartDateChange = (value) => {
  console.log('handleStartDateChange called with value:', value);
  // 当开始日期变化时，清空已选择的成员
  if (props.mode === 'transition') {
    formValueTransition.value.newCommittee.committeeMembers = [];
  }
};

// --- 处理编辑模式开始日期变化 ---
const handleEditStartDateChange = (value) => {
  console.log('handleEditStartDateChange called with value:', value);
  // 当开始日期变化时，清空已选择的成员
  if (props.mode === 'edit' || props.mode === 'add') {
    formValueEdit.value.committeeMembers = [];
  }
};

// --- 获取选中党员的详细信息 ---
const getSelectedMemberInfo = (memberId) => {
  // 直接从测试数据中查找
  return mockMembers.find(member => member.memberId === memberId);
};

// --- 成员管理函数 ---
const addCommitteeMember = () => {
  const newMember = createNewMember();
  if (props.mode === 'transition') {
    formValueTransition.value.newCommittee.committeeMembers.push(newMember);
  } else {
    formValueEdit.value.committeeMembers.push(newMember);
  }
};

const removeCommitteeMember = (index) => {
  if (props.mode === 'transition') {
    formValueTransition.value.newCommittee.committeeMembers.splice(index, 1);
  } else {
    formValueEdit.value.committeeMembers.splice(index, 1);
  }
};

const handleMemberSelect = (index, memberId) => {
  console.log('handleMemberSelect called with memberId:', memberId);
  
  // 首先从硬编码选项中查找
  let selectedOption = hardcodedOptions.find(option => option.value === memberId);
  
  // 如果没找到，再从计算选项中查找
  if (!selectedOption) {
    selectedOption = availableMembersOptions.value.find(option => option.value === memberId);
  }
  
  if (selectedOption) {
    // 从测试数据中查找党员信息
    const memberData = mockMembers.find(member => member.memberId === memberId);
    
    if (memberData) {
      console.log('Found member data:', memberData);
      
      // 更新表单中的党员信息
      if (props.mode === 'transition') {
        formValueTransition.value.newCommittee.committeeMembers[index].memberName = memberData.memberName;
        formValueTransition.value.newCommittee.committeeMembers[index].phoneNumber = memberData.phoneNumber;
      } else {
        formValueEdit.value.committeeMembers[index].memberName = memberData.memberName;
        formValueEdit.value.committeeMembers[index].phoneNumber = memberData.phoneNumber;
      }
    }
  }
};

// --- 初始化表单数据 ---
onMounted(() => {
  console.log('CommitteeEditor mounted with mode:', props.mode);
  console.log('mockMembers:', mockMembers);
  
  if (props.initialData) {
    if (props.mode === 'edit' || props.mode === 'add') {
      formValueEdit.value = {
        ...props.initialData,
        committeeMembers: props.initialData.committeeMembers ? [...props.initialData.committeeMembers] : [],
      };
    } else if (props.mode === 'transition') {
       formValueTransition.value.originalCommittee = { ...props.initialData };
    }
  }
});

// --- 工具函数 ---
const formatDate = (dateStr) => {
  if (!dateStr) return '未知日期';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
  } catch (e) {
    return dateStr;
  }
};

// --- 暴露给父组件的方法 ---
const validateAndGetData = async () => {
  try {
    if (props.mode === 'edit' || props.mode === 'add') {
      await formRefEdit.value?.validate();
      return { mode: props.mode, data: formValueEdit.value };
    }
    else if (props.mode === 'transition') {
      // 如果没有当前支委，则不需要验证结束日期
      if (!hasCurrentCommittee.value) {
        // 直接返回新支委信息，不包含结束日期
        return {
          mode: props.mode,
          data: {
            newCommittee: formValueTransition.value.newCommittee
          }
        };
      }
      await formRefTransition.value?.validate();
      return { mode: props.mode, data: formValueTransition.value };
    }
    return null;
  } catch (errors) {
    console.warn("表单验证失败:", errors);
    return null;
  }
};

defineExpose({ validateAndGetData });
</script>